#!/usr/bin/python
# -*- coding: utf-8 -*- 

"""     This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

"""

__author__ = "Evgeniy Frolov"
__email__ = "profisphantom@gmail.com"
__version__ = "2.0.1"

from traceback import print_exc


class QueryProcess(object):
    
    def __init__(self, Session, model, column, query_filter):
        self.model = model
        self.column = column
        if 'query' in query_filter:
            self.qvalue = query_filter['query']
            query_filter['query'] = self.like_filter
        self.query_filter = query_filter
        self.session = Session()
    
    def like_filter(self, queryobj):
        return queryobj.filter(self.column.like("%" + self.qvalue + "%"))
    
    def exec_query(self, query):
        if 'query' in self.query_filter:
            query = self.query_filter['query'](query)
        count = query.count()
        result = query.offset(self.query_filter['start'])\
                      .limit(self.query_filter['limit'])\
                      .all()
        return result, count
    
    def result_by_query(self, query):
        try:
            return self.to_answer(*self.exec_query(query))
        except Exception as e:
            print_exc()
            return self.get_error_answer(e)
    
    def get_query(self):
        return self.session.query(self.model)
    
    def __del__(self):
        if self.session:
            self.session.close()
    
    def result(self):
        try:
            return self.to_answer(*self.table_getter())
        except Exception as e:
            print_exc()
            return self.get_error_answer(e)
    
    def table_getter(self):
        if not self.query_filter:
            result = self.get_query().all()
            count = len(result)
        else:
            query = self.get_query()
            result, count = self.exec_query(query)
        return result, count
    
    def to_answer(self, data, count):
        result = []
        for i in data:
            result.append(i.raw_data())
        return {
            'total': count,
            'result': result,
            'success': True,
        }
    
    def get_error_answer(self, error):
        return {
            "success": False,
            "message": str(error)
        }